import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:library_base/entities/print_detail_entity.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:get/get.dart';
import 'package:library_base/provider/base_list_controller.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/channel.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:path_provider/path_provider.dart';

class PrintDetailController extends BaseListController<PrintDetailEntity, PrintDetailEntity> {

  List<String> ids = [];

  RxBool isConnected = false.obs;

  late List<GlobalKey> globalKeys = [];

  @override
  void onCreate() {
    enableLoadMore = false;
    isShowNoMoreFooter = false;
    ids = Get.arguments['ids'];
  }

  @override
  Future requestData() {
    isFirstLoading = true;
    requestGeneralListData(Apis.STOCK_OUT_ORDER_PRINT,
        isRefresh: false,
        method: FBResultFul.POST,
        params: {
          "ids": ids,
        });
    return super.requestData();
  }

  @override
  List<PrintDetailEntity> transformList(List<PrintDetailEntity> dataList, bool isRefresh) {
    return super.transformList(dataList, isRefresh);
  }

  @override
  Future onRefreshCallback() async {
    requestGeneralListData(Apis.STOCK_OUT_ORDER_PRINT,
        isRefresh: true,
        method: FBResultFul.POST,
        params: {
          "ids": ids,
        });
  }

  @override
  Future onLoadCallback() async {
    requestGeneralListData(Apis.STOCK_OUT_ORDER_PRINT,
        isRefresh: false,
        method: FBResultFul.POST,
        params: {
          "ids": ids,
        });
  }

  void tryReLoad() {
    isFirstLoading = true;
    multiControllerOut.viewStateChange(MultiStateStatus.loading);
    baseState?.setStateCallBack?.call();
    requestGeneralListData(Apis.STOCK_OUT_ORDER_PRINT,
        isRefresh: false,
        method: FBResultFul.POST,
        params: {
          "ids": ids,
        });
  }

  ///打印图片
  Future<void> onPrintSingle(PrintDetailEntity printDetailEntity,int index,GlobalKey globalKey) async {
    if(GetPlatform.isAndroid){
      if(isConnected.value){
        try{
          var bodyBytes = await _capturePng(globalKey,ratio:1.3);
          DateTime dateTime= DateTime.now();
          Directory? documentsDirectory = await getExternalStorageDirectory();
          String path = '${documentsDirectory!.path}${Platform.pathSeparator}printImage${Platform.pathSeparator}${dateTime.toString().substring(0,19)}$index.jpg';
          var file = await File(path).create(recursive: true);
          var newFile = await file.writeAsBytes(bodyBytes);
          if(await newFile.exists()){
            sendAndroidChannel.invokeMethod(PRINT_SINGLE,newFile.path);
          }
        }catch(e){
          ToastUtil.normal(e.toString());
        }
      }else{
        Get.toNamed(Routers.SEARCH_DEVICE_PAGE);
      }
    }else{
      ToastUtil.normal("暂不支持其他平台的打印");
    }
  }

  ///组件截图
  Future<Uint8List> _capturePng(GlobalKey globalKey,{double ratio = 1.0}) async {
    RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    var newRatio = 450/image.width.toDouble();

    ui.Image image1 = await boundary.toImage(pixelRatio: newRatio);
    ByteData? byteData1 = await image1.toByteData(format: ui.ImageByteFormat.png);
    Uint8List result1 =  byteData1!.buffer.asUint8List();
    return result1;

  }


  ///打印所有图片
  Future<void> onPrintAll() async {
    if(GetPlatform.isAndroid){
      var isShow = false;
      if(isConnected.value){
        DialogUtil.showLoadingCenterDialog(context!, content:MultiLanguage.printing.tr);
        isShow = true;
        try{
          String allPath = "";
          for(int i = 0;i<globalKeys.length;i++){
            var globalKey = globalKeys[i];
            var bodyBytes = await _capturePng(globalKey,ratio:1.2);
            DateTime dateTime= DateTime.now();
            Directory? documentsDirectory = await getExternalStorageDirectory();
            String path = '${documentsDirectory!.path}${Platform.pathSeparator}printImage${Platform.pathSeparator}${dateTime.toString().substring(0,19)}$i.jpg';
            var file = await File(path).create(recursive: true);
            var newFile = await file.writeAsBytes(bodyBytes);
            if(i == (globalKeys.length - 1)){
              allPath = allPath + newFile.path;
            }else{
              allPath = allPath + newFile.path + "|";
            }
            if(await newFile.exists()){
              sendAndroidChannel.invokeMethod(PRINT_ALL,newFile.path);
            }
          }
          sendAndroidChannel.invokeMethod(PRINT_ALL,allPath);
        }catch(e){
          if(isShow){
            Get.back();
          }
          ToastUtil.normal(e.toString());
        }
      }else{
        Get.toNamed(Routers.SEARCH_DEVICE_PAGE);
      }
    }else{
      ToastUtil.normal("暂不支持其他平台的打印");
    }
  }

}
